package es.ojugames.myplaces.database;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class MyPlacesProvider extends ContentProvider {
	public static final String PROVIDER_NAME = "es.ojugames.myplaces";
	public static final Uri PLACES_URI = Uri.parse("content://" + PROVIDER_NAME + "/places");
		
	private static final int PLACES = 1;
	private static final int PLACES_ID = 2;
	
	//URI's Validas
	private static final UriMatcher uriMatcher; static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(PROVIDER_NAME, "places", PLACES);
		uriMatcher.addURI(PROVIDER_NAME, "places/#", PLACES_ID);
	}
		
	private SQLiteDatabase myplacesDB;

	//Comprobacion de si la URI hace referencia a un registro o a un conjunto de estos
	//Los conjuntos estaran referenciados con constantes pares (preparado por si tuvieramos mas tablas)
	@Override
	public String getType(Uri uri) {
		if (uriMatcher.match(uri) % 2 == 1) {
			return "vnd.android.cursor.dir/vnd.ojugames.myplaces";
		} else if (uriMatcher.match(uri) % 2 == 0) {
			return "vnd.android.cursor.item/vnd.ojugames.myplaces";
		} else {
			throw new IllegalArgumentException("Uri no soportada: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		String tabla = "";
		Uri contentUri = null;
		
		if (uriMatcher.match(uri) == PLACES) {
			tabla = ConstantsDB.Places.TABLE_NAME;
			contentUri = PLACES_URI;
		}
		
		long rowID = myplacesDB.insert(tabla, "", values);
		
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(contentUri, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		} else {
			throw new SQLException("Error insertando el registro");
		}
	}

	@Override
	public boolean onCreate() {
		Context context = getContext();
		MyPlacesSQLHelper dbHelper = new MyPlacesSQLHelper(context);
		myplacesDB = dbHelper.getWritableDatabase();
		
		return (myplacesDB == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
			String sortOrder) {
		
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		
		if (uriMatcher.match(uri) == PLACES || uriMatcher.match(uri) == PLACES_ID) {
			sqlBuilder.setTables(ConstantsDB.Places.TABLE_NAME);
			if (sortOrder == null || sortOrder == "") {
				sortOrder = ConstantsDB.Places.DEFAULT_SORT_ORDER;
			}
			if  (uriMatcher.match(uri) % 2 == 0) {
				sqlBuilder.appendWhere(ConstantsDB.Places._ID + " = " + uri.getPathSegments().get(1));
			}
		}		
		
		Cursor c = sqlBuilder.query(myplacesDB, projection, selection, selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		
		return c;
	}

	
	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		String tabla = "";
		
		if (uriMatcher.match(uri) == PLACES_ID) {
			tabla = ConstantsDB.Places.TABLE_NAME;
		}
		
		String id = uri.getPathSegments().get(1);
		int count = myplacesDB.update(tabla, values, ConstantsDB.Places._ID
				+ " = "
				+ id
				+ (!TextUtils.isEmpty(selection) ? " AND (" + selection
						+ ")" : ""), selectionArgs);
		
		getContext().getContentResolver().notifyChange(uri, null);
		return count;

	}
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		String tabla = "";
		int res;
		
		if (uriMatcher.match(uri) == PLACES_ID) {
			tabla = ConstantsDB.Places.TABLE_NAME;
		}

		String id = uri.getPathSegments().get(1);
		
		res = myplacesDB.delete(tabla,
				ConstantsDB.Places._ID
							+ " = "
							+ id
							+ (!TextUtils.isEmpty(selection) ? " AND (" + selection
									+ ")" : ""), selectionArgs);
		
		// Notificamos el cambio al sistema y devolvemos el numero de filas
		// afectadas
		getContext().getContentResolver().notifyChange(uri, null);
		return res;
	}

}
